package server.alarmThreads;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

import org.apache.log4j.Logger;

import server.AlarmServerMain;
import server.config.ServerConfig;
import server.db.SQL;

public class OnlineCheckerThread {

	private static OnlineCheckerThread self;

	/**
	 * 
	 */
	private static Logger logger = Logger.getLogger(AlarmServerMain.class);

	/**
	 * 
	 */
	private long lastAlarm = 0;

	/**
	 * 
	 */
	private OnlineCheckerThread() {

		lastAlarm = System.currentTimeMillis();
		startOnlineCheckerThread();
		logger.info("OnlineChecker started");
	}

	public static OnlineCheckerThread getInstance() {

		if (self == null) {
			self = new OnlineCheckerThread();
		}
		return self;
	}

	/**
	 * 
	 */
	private void startOnlineCheckerThread() {

		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {

				boolean running = true;
				while (running) {

					try {
						Thread.sleep(60 * 1000);
						if (lastAlarm < System.currentTimeMillis()
								- (ServerConfig.getInstance().getOnlineCheckTimerOut() * 60 * 1000)) {
							logger.error("Lastalarm abgelaufen");
							continue;
						}
						if (istServerOK()) {
							Scanner s = new Scanner(
									new URL(
											"http://chrku.de/alarmapp/checkServerOnline.php?alarmappserveronline=true")
											.openStream());
							s.next();
							s.close();
						} else {
							logger.error("Server nicht OK");
						}
					} catch (MalformedURLException e) {
						e.printStackTrace();
					} catch (Exception e) {
						logger.error("Server nicht OK Exception: ", e);
						e.printStackTrace();
					}
				}

			}
		});
		t.start();
	}

	public boolean istServerOK() {

		return sqlOK() && internetOk() ;
	}

	private boolean internetOk() {

		try {
			Scanner s = new Scanner(
					new URL("http://www.google.com").openStream());
			s.next();
			Scanner s2 = new Scanner(new URL(
					"http://alarmapp.chrku.de/alarm/index.php").openStream());
			if(!s2.next().startsWith("<!DOC")) {
				System.out.println("Apache offline");
				s2.close();
				s.close();
				return false;
			}
			s.close();
			s2.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	private boolean sqlOK() {

		try {
			if (SQL.getInstance().getConPool().connectionOk()) {
				return true;
			}
			else {
				System.out.println("SQL Connection nicht ok");
				return false;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 
	 */
	public void updateLastAlarm() {

		lastAlarm = System.currentTimeMillis();
	}

}
